﻿using CommandService;
using Entity;
using Entity.SysEntity;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SysFrameWork
{
    public class PowerBLL : PubMethods
    {
        OperateModel oper;
        ReturnResult rsl;
        Commands cmd;
        LoginInfo userLogin;
        List<OperateModel> operList;
        public PowerBLL()
        {
            cmd = new Commands();
            oper = new OperateModel();
            userLogin = new LoginInfo();
            operList = new List<OperateModel>();
        }
        /// <summary>
        /// 权限角色添加
        /// </summary>
        /// <param name="datas"></param>
        /// <returns></returns>
        public ReturnResult UpdatePowerRole(string datas)
        {
            rsl = new ReturnResult();
            try
            {
                var role = JsonConvert.DeserializeObject<DbPowerRole>(datas);
                oper = new OperateModel();
                if (role.id == null || role.id == 0)
                {
                    role.isDel = 0;
                    role.createtime = getNow();
                    role.createuser = userLogin.UserInfo().userCode;
                    role.groupCode = "R" + getTimeString();
                    role.status = "Y";
                    oper.Types = OperateModel.OperateType.Add;
                }
                else
                {
                    oper.Types = OperateModel.OperateType.Edit;
                    oper.Conditions = "id";
                }
                oper.Data = role;
                operList = new List<OperateModel>();
                operList.Add(oper);
                rsl = cmd.MoreUpdate(operList);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 权限角色列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageCount"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public ReturnResult getPowerRoleList(string pageIndex, string pageSize, ref string pageCount, string condition)
        {
            rsl = new ReturnResult();
            try
            {
                if (string.IsNullOrWhiteSpace(pageIndex))
                {
                    pageIndex = "1";
                }
                if (string.IsNullOrWhiteSpace(pageSize))
                {
                    pageSize = Tools.ConfigReader.Reader["PageSize"];
                }
                StringBuilder sb = new StringBuilder();
                sb.Append(" isdel=0  ");
                sb = CreateSelectCondition(sb,condition);
                var list = cmd.PageList("V_powerRole_info", pageIndex, pageSize, sb.ToString(), "id desc", ref pageCount);

                rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 根据id获取权限角色信息
        /// </summary>
        /// <param name="dataId"></param>
        /// <returns></returns>
        public ReturnResult getRoleById(string dataId)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from sys_powerConfig_groups where id="+dataId);
                var table = cmd.GetDataTable(sb.ToString());
                rsl.Data = cmd.TableToDictionary(table);
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 根据角色编码获取角色权限
        /// </summary>
        /// <param name="groupCode"></param>
        /// <param name="menuCode"></param>
        /// <returns></returns>
        public ReturnResult getRolePowerByCode(string groupCode, string menuCode)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select top 1 * from sys_powerConfig_groupPower where ");
                sb.Append(" groupCode='" + groupCode + "' and ");
                sb.Append("menuCode='" + menuCode + "'");
                var table = cmd.GetDataTable(sb.ToString());
                rsl.Result = true;
                if (table.Rows.Count > 0)
                {
                    rsl.Data = table.Rows[0]["operates"].ToString().ToLower();
                }
                else
                {
                    rsl.Data = "";
                    rsl.Message = "没有数据";
                }
              

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 保存角色配置权限
        /// </summary>
        /// <param name="groupCode">角色编码</param>
        /// <param name="menuCode">菜单编码</param>
        /// <param name="powers">权限集合</param>
        /// <returns></returns>
        public ReturnResult SaveRolePower(string groupCode, string menuCode, string powers)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                if (string.IsNullOrWhiteSpace(groupCode))
                {
                    rsl.Message = "权限角色不允许为空"; return rsl;
                }
                if (string.IsNullOrWhiteSpace(powers))
                {
                    sb.Append("delete from sys_powerConfig_groupPower where ");
                    sb.Append(" groupCode='" + groupCode.Trim() + "' and ");
                    sb.Append("menuCode='" + menuCode + "'");
                    rsl = cmd.UpdateSql(sb.ToString());
                }
                else
                {

                    sb.Append("select top 1 * from sys_powerConfig_groupPower where ");
                    sb.Append(" groupCode='" + groupCode.Trim() + "' and ");
                    sb.Append("menuCode='" + menuCode + "'");
                    var table = cmd.GetDataTable(sb.ToString());
                    bool isAdd = true;
                    if (table.Rows.Count > 1)
                    {
                        rsl.Message = "权限存在重复"; return rsl;
                    }
                    else
                    {
                        if (table.Rows.Count > 0)
                        {
                            isAdd = false;
                        }
                    }
                    #region 更新方法
                    DbRolePowers p = new DbRolePowers();
                    p.menuCode = menuCode;
                    p.operates = powers;
                    p.groupCode = groupCode;
                    if (isAdd)
                    {
                        p.createtime = DateTime.Now.ToString();
                        p.createuser = userLogin.UserInfo().userCode;
                        rsl = cmd.Add(p);
                    }
                    else
                    {
                        OperateModel oper = new OperateModel();
                        oper.Data = p;
                        oper.Types = OperateModel.OperateType.Edit;
                        oper.Conditions = "groupCode,menuCode";
                        rsl = cmd.Edit(oper);
                    }
                    #endregion
                }


            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 获取用户权限
        /// </summary>
        /// <param name="userCode"></param>
        /// <param name="menuCode"></param>
        /// <returns></returns>
        public ReturnResult GetUserPower(string userCode,string menuCode)
        {
            rsl = new ReturnResult();
            try
            {
                string isAdmin = "", roleCode = "" ;
                StringBuilder sb = new StringBuilder();
                #region 人员身份信息
                if (string.IsNullOrWhiteSpace(userCode))
                {
                    userCode = userLogin.UserInfo().userCode;
                    isAdmin = userLogin.UserInfo().isAdmin.ToString();
                    roleCode = userLogin.UserInfo().powerRole;
                }
                else
                {
                    sb.Append("select isAdmin,powerRole from sys_users_info where userCode='" + userCode + "' ");
                    var table = cmd.GetDataTable(sb.ToString());
                    if (table.Rows.Count <= 0)
                    {
                        rsl.Result = false;
                        rsl.Message = "没有获取人员:" + userCode + "的信息";
                        return rsl;
                    }
                    isAdmin = table.Rows[0]["isAdmin"].ToString();
                    roleCode = table.Rows[0]["powerRole"].ToString();
                }
                #endregion

                sb.Clear();

                if (string.IsNullOrWhiteSpace(menuCode))
                {
                    rsl.Message = "菜单编码获取失败";
                    rsl.Result = true;
                    return rsl;
                }

                #region 页面标准权限
                string webPowers = "";
                sb.Append("select isnull(operate,'') oper from sys_MenuInfo where status='Y' and isdel=0");
                sb.Append(" and menuCode='" + menuCode + "' ");
                var wpTable = cmd.GetDataTable(sb.ToString());
                if (wpTable.Rows.Count > 0 && !string.IsNullOrWhiteSpace(wpTable.Rows[0]["oper"].ToString()))
                {
                    webPowers = wpTable.Rows[0]["oper"].ToString().Split(';')[0].Trim();
                }
                #endregion

                string userPower = "";
                if (isAdmin != "1")
                {
                    #region 非管理员-根据权限获取全部权限
                    sb.Clear();
                    sb.Append("select top 1 * from sys_powerConfig_groupPower where ");
                    sb.Append(" groupCode='" + roleCode + "' and menuCode='" + menuCode + "'");
                    var table = cmd.GetDataTable(sb.ToString());
                    rsl.Result = true;
                    if (table.Rows.Count > 0)
                    {
                        userPower = table.Rows[0]["operates"].ToString().Trim();
                    }
                    #endregion
                }
                else
                {//管理员权限
                    userPower = webPowers;
                }
                Dictionary<string, string> dic = new Dictionary<string, string>();
                dic["webPower"] = webPowers;//页面标准权限
                dic["userPower"] = userPower;//人员权限
                rsl.Data = dic;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 删除权限角色
        /// </summary>
        /// <param name="dataId">数据id</param>
        /// <returns></returns>
        public ReturnResult DelRolePowers(int dataId)
        {
            rsl = new ReturnResult();
            try
            {
                oper = new OperateModel();
                DbPowerRole p = new DbPowerRole();
                p.id = dataId;
                p.isDel = 1;
                p.delDate = DateTime.Now.ToString("yyyy-MM-dd");
                p.delUser = userLogin.UserInfo().userCode;
                p.status = "N";
                oper.Types= OperateModel.OperateType.Edit;
                oper.Data = p;
                oper.Conditions = "id";
                rsl = cmd.Edit(oper);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

    }
}
